const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const webpack = require('webpack');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
 
function createHtmlPlugin(template, filename, chunks) {
  return new HtmlWebpackPlugin({
    template: path.resolve(__dirname,  template),
    filename: path.resolve(__dirname,  filename),
    useCdn: process.env.NODE_ENV  === 'production', // 生产模式下使用 CDN 引用的地址 
    chunks: chunks, // 引入哪些打包后的模块（和 entry 的 key 一致）
  });
}
 
const config = {
  mode: 'development',
  entry: {
    login: path.resolve(__dirname,  'src/login/index.js'), 
    content: path.resolve(__dirname,  'src/content/index.js'), 
    publish: path.resolve(__dirname,  'src/publish/index.js'), 
    analysis: path.resolve(__dirname,  'src/analysis/index.js'), 
    leaderboard: path.resolve(__dirname,  'src/leaderboard/index.js'), 
    annual_character: path.resolve(__dirname,  'src/annual_character/index.js'), 
    answer_analysis: path.resolve(__dirname,  'src/answer_analysis/index.js'), 
    Hero_of_The_Times: path.resolve(__dirname,  'src/Hero_of_The_Times/index.js'), 
    entrance: path.resolve(__dirname,  'src/entrance/index.js'), 
    introduction: path.resolve(__dirname,  'src/introduction/index.js'), 
    reader_feedback: path.resolve(__dirname,  'src/reader_feedback/index.js'), 
    social_character: path.resolve(__dirname,  'src/social_character/index.js'), 
    super_hero: path.resolve(__dirname,  'src/super_hero/index.js'), 
  },
  output: {
    path: path.resolve(__dirname,  'dist'),
    filename: './[name]/index.js', 
    clean: true, // 生成打包后的内容之前，清空输出的目录 
  },
  // 插件 
  plugins: [
    new MiniCssExtractPlugin({
      filename: './[name]/index.css', 
    }),
    // root index to redirect to entrance for dev convenience
    createHtmlPlugin('public/index.html',  'dist/index.html',  []),
    createHtmlPlugin('public/annual_character.html',  'dist/annual_character/index.html',  ['annual_character']),
    createHtmlPlugin('public/answer_analysis.html',  'dist/answer_analysis/index.html',  ['answer_analysis']),
    createHtmlPlugin('public/Hero_of_The_Times.html',  'dist/Hero_of_The_Times/index.html',  ['Hero_of_The_Times']),
    createHtmlPlugin('public/entrance.html',  'dist/entrance/index.html',  ['entrance']),
    createHtmlPlugin('public/introduction.html',  'dist/introduction/index.html',  ['introduction']),
    createHtmlPlugin('public/reader_feedback.html',  'dist/reader_feedback/index.html',  ['reader_feedback']),
    createHtmlPlugin('public/social_character.html',  'dist/social_character/index.html',  ['social_character']),
    createHtmlPlugin('public/super_hero.html',  'dist/super_hero/index.html',  ['super_hero']),
    createHtmlPlugin('public/login.html',  'dist/login/index.html',  ['login']),
    createHtmlPlugin('public/content.html',  'dist/content/index.html',  ['content']),
    createHtmlPlugin('public/publish.html',  'dist/publish/index.html',  ['publish']),
    createHtmlPlugin('public/analysis.html',  'dist/analysis/index.html',  ['analysis']),
    createHtmlPlugin('public/leaderboard.html',  'dist/leaderboard/index.html',  ['leaderboard']),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV':  JSON.stringify(process.env.NODE_ENV), 
    }),
    new CleanWebpackPlugin({
      cleanOnceBeforeBuildPatterns: ['**/*', '!.git'], // 排除 .git 文件夹 
    }),
  ],
  // 加载器 
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: [process.env.NODE_ENV === 'development' ? 'style-loader' : MiniCssExtractPlugin.loader,  'css-loader'],
      },
      {
        test: /\.less$/i,
        use: [
          process.env.NODE_ENV  === 'development' ? 'style-loader' : MiniCssExtractPlugin.loader, 
          'css-loader',
          'less-loader',
        ],
      },
      {
        test: /\.(png|jpg|gif|jpeg)$/i,
        type: 'asset',
        generator: {
          filename: 'assets/[hash][ext][query]',
        },
      },
      {
        test: /\.(ttf|otf|eot|woff|woff2)$/i,
        type: 'asset/resource',
        generator: {
          filename: 'fonts/[hash][ext][query]',
        },
      },
      {
        test: /\.md$/,
        use: [
          {
            loader: 'html-loader',
          },
          {
            loader: 'markdown-loader',
            options: {
              // 可以根据需要配置 Markdown 解析选项 
            },
          },
        ],
      },
    ],
  },
  // 优化 
  optimization: {
    minimizer: [
      `...`,
      new CssMinimizerPlugin(),
      new TerserPlugin({
        terserOptions: {
          compress: {
            drop_console: true, // 移除 console 语句 
          },
        },
      }),
    ],
    splitChunks: {
      chunks: 'all',
    },
  },
  // 外部依赖 
  externals: {
    wangeditor: 'window.wangEditor', 
  },
  // 解析 
  resolve: {
    alias: {
      '@': path.resolve(__dirname,  'src'),
    },
  },
  // 开发服务器配置 
  devServer: {
    port: 52331, // 设置开发服务器端口为 52331 
    hot: true, // 启用热更新 
    open: true, // 自动打开浏览器 
    static: {
      directory: path.join(__dirname,  'dist'), // 静态资源目录 
    },
  },
};
 
if (process.env.NODE_ENV  === 'development') {
  config.devtool  = 'inline-source-map';
}
 
// 防止 import 的包被异常处理 
if (process.env.NODE_ENV  === 'production') {
  config.externals  = {
    // key: import from 语句后面的字符串 
    // value: 留在原地的全局变量（最好和 CDN 在全局暴露的变量一致）
    'bootstrap/dist/css/bootstrap.min.css':  'bootstrap',
    axios: 'axios',
    'form-serialize': 'serialize',
    '@wangeditor/editor': 'wangEditor',
  };
}
 
module.exports  = config;